import { LoginResponse } from '@global/types'
import { defineStore } from 'pinia'
import { IS_ELECTRON } from './useEnv'
interface UserInfo extends LoginResponse {
  lastSendTime?: number
  saveDownloadFilePath: string
}

const userInfoCache: UserInfo = Object.assign(
  {
    locale: 'zhCN',
    id: undefined,
    name: '',
    phone: '',
    token: '',
    saveDownloadFilePath: ''
  },
  JSON.parse(localStorage.getItem('userInfo') || '{}')
)

const useUserInfo = defineStore('userInfo', {
  state: () => userInfoCache,
  persist: true,
  actions: {
    async init() {
      this.initSaveDownloadFilePath()
    },
    /** 初始化下载文件的保存路径 */
    async initSaveDownloadFilePath() {
      if (!IS_ELECTRON) return
      if (!this.saveDownloadFilePath) {
        const { $postMessage } = await import('@/utils/ipcRenderer')
        const { ipcRenderer } = await import('electron')
        $postMessage(({ app, mainWin }) => {
          mainWin.webContents.send('get-desktop-path', app.getPath('desktop'))
        })
        await new Promise(resolve => {
          ipcRenderer.once('get-desktop-path', (_, path) => {
            this.saveDownloadFilePath = path
            resolve(path)
          })
        })
      } else return this.saveDownloadFilePath
    }
  }
})

export default useUserInfo
